//sheet.js中文官方文档地址：  https://xlsx.nodejs.cn/docs/getting-started/examples/import#extract-raw-data
import * as XLSX from 'xlsx';


async function readXLSXFileData(fileName) {
    try {
        if(!fileName){
            fileName = 'webList';
        }
        const file = `/home/excelData/${fileName}.xlsx`;
        let result = await (await fetch(file)).arrayBuffer();
        result = new Uint8Array(result);
        const workbook = XLSX.read(result, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        console.log('Data:'+fileName, data);
        return data;
    } catch (error) {
        console.error('Error reading XLSX file:', error);
        throw error;
    }
}


async function readXLSXFile(file) {
    try {
        let result = await (await fetch('/home/excelData/webList.xlsx')).arrayBuffer();
        result = new Uint8Array(result);
        console.log(result, 'jdsjflksjflsj')
        const workbook = XLSX.read(result, { type: 'array' });
        console.log('Workbook:', workbook);
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        console.log(sheetName, worksheet, 'worksheet');
        const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        
        console.log('Data:', data);
        return data;

    } catch (error) {
        console.error('Error reading XLSX file:', error);
        throw error;
    }
}
function writeXLSXFile(filePath, data) {
    try {
        const worksheet = XLSX.utils.json_to_sheet(data);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
        XLSX.writeFile(workbook, filePath);
    } catch (error) {
        console.error('Error writing XLSX file:', error);
        throw error;
    }
}
export default { readXLSXFile, writeXLSXFile, readXLSXFileData };

